package org.zjt.book.akkatest

import java.util.concurrent.TimeUnit

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Success, Failure}
/**
  * Created by Administrator on 2017/5/8.
  */
object FutureAkka extends App{


  // create a Future
  def grind(beans: Int): Future[Int] = Future{
    println("happy brewing :)")
    Thread.sleep(2000)
    println("it's brewed!")
    2121+2121+beans
  }


  /**
    * Future类中导入Future实例提供的隐式转换器：
    *     import Future.{ InternalCallbackExecutor => internalExecutor }
    *       ExecutionContextExecutorz中定义了多种隐式转换器。
     */

  // this isblocking(blockingisbad)
  val result=Await.result(grind(2121),Duration(10.0,TimeUnit.SECONDS))


  val var2 = grind(2121)
  Thread.sleep(1000)
  var2.onComplete{ case ground => println(s"okay, got my ground coffee $ground")}


  var2 onComplete {
      case Success(ground) => println(s"got my $ground")
      case Failure(ex) => println("This grinder needs a replacement, seriously!")
    }


  var2.onSuccess{
    case ground => println(s"error, got my ground coffee$ground")
  }


  // 如果Future没有在Await规定的时间里返回,
  // 将抛出java.util.concurrent.TimeoutException
  println(result)
  Thread.sleep(1000)

}
